package com.study.util;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import com.alibaba.druid.filter.config.ConfigTools;

/**
 * alibaba druid加解密规则，明文密码+私钥（privateKey）加密=加密密码<br>
 * 加密密码+公钥（publicKey）解密=明文密码
 * 
 * @author chenk
 *
 */
public class DruidEncryptorUtils {

	private static String privateKey;

	private static String publicKey;

	static {
		try {
			String[] keyPair = ConfigTools.genKeyPair(512);
			privateKey = keyPair[0];
			System.out.println(String.format("privateKey--->%s", privateKey));

			publicKey = keyPair[1];
			System.out.println(String.format("publicKey--->%s", publicKey));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
	}

	public static String encode(String plainText) {
		String cipherText = null;
		try {
			cipherText = ConfigTools.encrypt(privateKey, plainText);
			System.out.println("加密后的字符串：" + cipherText);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return cipherText;
	}

	public static String decode(String cipherText) {
		String plainText = null;
		try {
			plainText = ConfigTools.decrypt(publicKey, cipherText);
			System.out.println("解密后的字符串：" + plainText);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return plainText;
	}

	public static void main(String[] args) {
		String encode = encode("root");
		System.out.println(encode);
		String decode = decode(encode);
		System.out.println(decode);
	}

}
